<?php
/**
 * common repository file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/03
 * Time: 15:20
 */

namespace HiCommon\Repository;

use HiCommon\Model\Shop;
use DB;

class ShopRepository extends BaseRepository
{
    public function base_model()
    {
        return new \HiCommon\Model\Shop();
    }


    public function total_status_count()
    {

        $arr_select = ['status', DB::raw('count(*) as total_count')];
        $result     = self::base_model()
                          ->whereIn('status', [0, 1, 3])
                          ->groupBy('status')
                          ->get($arr_select);
        return $result;
    }

    public function total_cate_count()
    {

        $arr_select = ['cate', DB::raw('count(*) as total_count')];
        $result     = self::base_model()
                          ->whereIn('cate', [1, 2, 3])
                          ->where('status', 1)
                          ->groupBy('cate')
                          ->get($arr_select);
        return $result;
    }

    /**
     * 根据条件查询一条数据
     */
    public function get_where_one(array $where = [], $arr_field = ['*'])
    {
        return Shop::where($where)->select($arr_field)->first();
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all($arr_option = [])
    {
        return Shop::commonget($arr_option);
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     * @param array $arr_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function find_one($n_id = 0, $arr_field = ['*'])
    {
        return Shop::select($arr_field)->find($n_id);
    }

    /**
     * 查询一条数据
     *
     * @param array $arr_where
     * @param array $arr_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function select_one_by_where($arr_where = [], $arr_field = ['*'])
    {
        return Shop::where($arr_where)->select($arr_field)->first();
    }

    /**
     * 分页获取数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($search = [], $with)
    {
        $model = new Shop();
        if (isset($search['name']) && $search['name']) {
            $model = $model->where('name', 'like', '%' . $search['name'] . '%');
        }
        if (isset($search['phone']) && $search['phone']) {
            $model = $model->where('phone', $search['phone']);
        }
        if (isset($search['cate']) && $search['cate']) {
            $model = $model->where('cate', $search['cate']);
        }
        if (isset($search['province']) && $search['province']) {
            $model = $model->where('province', $search['province']);
        }
        if (isset($search['city']) && $search['city']) {
            $model = $model->where('city', $search['city']);
        }
        if (isset($search['area']) && $search['area']) {
            $model = $model->where('area', $search['area']);
        }
        return $model->where(['status'=>1])->commonpage($with);
    }

    /**
     * 分页获取数据-小程序前端获取检测机构列表
     *
     * @param array $arr_search
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_list($arr_search = [])
    {
        $longitude = empty($arr_search['longitude']) ? 0 : $arr_search['longitude'];
        $latitude = empty($arr_search['latitude']) ? 0 : $arr_search['latitude'];

        $arr_where = hi_array_del_null(array_remain($arr_search, ['province', 'city', 'area']));
        $arr_sort = array_remain($arr_search, ['sort_key', 'sort_method']);
        if (!isset($arr_sort['sort_key'])) {
            $arr_sort['sort_key'] = 'distance';
        }
        if (!isset($arr_sort['sort_method'])) {
            $arr_sort['sort_method'] = 'asc';
        }

        $arr_with = ['type', 'checkpoint_service_type', 'province_name', 'city_name', 'area_name', 'shop_score'];
        /*$s_field_distance = DB::raw("(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($longitude-longitude)/360),2)+COS(PI()*$latitude/180)* COS(latitude * PI()/180)*POW(SIN(PI()*($latitude-latitude)/360),2)))) as distance");//旧的计算距离，误差比较大*/

        /*新的计算距离方式，误差较小*/
//        $s_field_distance = DB::raw("( 2 * 6378.137 * asin(sqrt(pow(sin((deg2rad($latitude) - deg2rad(latitude)) / 2), 2) + cos(deg2rad($latitude)) * cos(deg2rad(latitude)) * pow(sin((deg2rad($longitude) - deg2rad(longitude)) / 2), 2)))) as distance");


        $s_field_distance = DB::raw("( 2 * 6378.137 * asin(sqrt(pow(sin((pi()/180*($latitude) - pi()/180*(latitude)) / 2), 2) + cos(pi()/180*($latitude)) * cos(pi()/180*(latitude)) * pow(sin((pi()/180*($longitude) - pi()/180*(longitude)) / 2), 2)))) as distance");


        $arr_select = [
            'id', 'name', 'type', 'logo', 'phone', 'province', 'city', 'check_score', 'area', 'address', 'longitude', 'latitude', 'extend', $s_field_distance

        ];
        $arr_option = [
            'field' => $arr_select,
            'with' => $arr_with,
            'where' => $arr_where,
            'order' => ['key' => $arr_sort['sort_key'], 'value' => $arr_sort['sort_method']],
        ];
        $res = Shop::where('cate', 1)
            ->where(
                function ($query)
                use ($arr_search) {
                    if (!empty($arr_search['key_word'])) {
                        $s_key_word = trim($arr_search['key_word']);
                        $query->where('name', 'like', '%' . $s_key_word . '%');
                    }
                })
            ->apipage($arr_option);

        return $res;
    }

    /**
     * 检测机构-商家详情 [商家详情+时间段+年检费用]
     *
     * @param array $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_detail($n_id)
    {
        $arr_with = ['type', 'checkpoint_service_type', 'province_name', 'city_name', 'area_name', 'appointment_day', 'shop_score'];
        $arr_select = ['id', 'name', 'type', 'logo', 'phone', 'province', 'city', 'area', 'address', 'longitude', 'latitude', 'expenses', 'check_score', 'extend'];
        $res = Shop::with($arr_with)
            ->select($arr_select)
            ->find($n_id);

        return $res;
    }


    /**
     * 用户端APP接口（获取维修店列表）
     * @param array $option
     * @return mixed
     */
    public function api_get_shop_list($option = [])
    {
        $longitude = $option['lon'];
        $latitude = $option['lat'];
        $arr_with = ['area_name'];
        $withCount = ['store_order_num', 'repair_order_num']; //普通订单和服务订单数据统计

        $s_field_distance = DB::raw("( 2 * 6378.137 * asin(sqrt(pow(sin((pi()/180*($latitude) - pi()/180*(latitude)) / 2), 2) + cos(pi()/180*($latitude)) * cos(pi()/180*(latitude)) * pow(sin((pi()/180*($longitude) - pi()/180*(longitude)) / 2), 2)))) as distance");
        //$s_field = DB::raw("( 2 * 6378.137 * asin(sqrt(pow(sin((pi()/180*($latitude) - pi()/180*(latitude)) / 2), 2) + cos(pi()/180*($latitude)) * cos(pi()/180*(latitude)) * pow(sin((pi()/180*($longitude) - pi()/180*(longitude)) / 2), 2))))");

        $arr_select = ['id', 'name', 'company_name', 'logo', 'address', 'shop_type', 'area', 'extend', 'longitude', 'latitude', 'score', $s_field_distance];

        $model = new Shop();

        if (isset($option['type']) && $option['type']) {
            $model = $model->where('shop_type', $option['type']);
        }

        if (isset($option['city']) && $option['city']) {
            $model = $model->where('city', $option['city']);
        }

        if (isset($option['area']) && $option['area']) {
            $model = $model->where('area', $option['area']);
        }

        if ($option['sort'] == 'score') {
            $model = $model->orderBy('score', 'desc')->orderBy('distance', 'asc');
        } else {
            //$model = $model->where($s_field, '<=', $option['distance']);//在某个距离范围内的数据
            $model = $model->orderBy('distance', 'asc')->orderBy('score', 'desc');//默认距离由近到远
        }
        $result = $model->select($arr_select)
            ->with($arr_with)
            ->where(['status' => 1, 'state' => 1, 'cate' => 2])
            ->withCount($withCount)
            ->paginate();

        return $result;
    }

    /**
     * 通过where分页获取数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list_by_where($arr_where, $arr_option = [])
    {
        return Shop::where($arr_where)->commonpage($arr_option);
    }

    /**
     * 根据条件统计数量
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_where($arr_where)
    {
        return Shop::where($arr_where)->count();
    }

    /**
     * 根据条件统计总和
     *
     * @param array $arr_where
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_sum_by_where($arr_where = [], $s_field = 'mark')
    {
        return Shop::where($arr_where)->sum($s_field);
    }

    /**
     * 根据条件批量删除信息
     *
     * @param array $arr_where
     * @param bool $method
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_by_where($arr_where = [], $method = false)
    {
        return Shop::where($arr_where)->commondelete($method);
    }

    /**
     * 通过where获取一条数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one_by_where($arr_where, $arr_option = [])
    {
        return Shop::where($arr_where)->commonfirst($arr_option);
    }

    /**
     * @param $arr_where
     * @param array $arr_option
     * @return mixed
     */
    public function data_monitoring($arr_where = [], int $nid)
    {
        return Shop::where($arr_where)
            ->where(function ($query)
            use ($nid) {
                if (!empty($nid)) {
                    $query->where('id', '!=', $nid);
                }
            })->count();
    }

    /**
     * 添加一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_one($arr_input)
    {
        return Shop::create($arr_input);
    }

    /**
     * 添加多条数据
     *
     * @param array $arr_data
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_many($arr_data)
    {
        return Shop::insert($arr_data);
    }

    /**
     * 查询一条数据（APP接口用）
     */
    public function get_one($option)
    {
        $arr_select = ['id', 'name', 'company_name', 'logo', 'address', 'shop_type', 'area', 'longitude', 'latitude', 'extend', 'phone', 'start_time', 'end_time', 'score'];

        /*if (!empty($option['lon']) && !empty($option['lat'])) {
            $longitude = $option['lon'];
            $latitude = $option['lat'];

            $field_distance = DB::raw("(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($longitude-longitude)/360),2)+COS(PI()*$latitude/180)* COS(latitude * PI()/180)*POW(SIN(PI()*($latitude-latitude)/360),2)))) as distance");
            $arr_select[] = $field_distance;
        }*/

        $withCount = ['store_order_num', 'repair_order_num']; //普通订单和服务订单数据统计
        $result = Shop::select($arr_select)
            ->where($option['where'])
            ->with($option['with'])
            ->withCount($withCount)
            ->first();

        return $result;
    }

    /**
     * 更新或新建一条数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_or_create($arr_where, $arr_input)
    {
        return Shop::updateOrCreate($arr_where, $arr_input);
    }

    /**
     * 修改一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_one(array $arr_input)
    {
        return Shop::where('id', $arr_input['id'])->update($arr_input);
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one(int $n_id)
    {
        return Shop::where('id', $n_id)->commondelete();
    }

    /**
     * 根据条件修改一条数据状态
     *
     * @param int $n_id
     * @param int $n_state
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_data(array $map, array $up_data)
    {
        return Shop::where($map)->update($up_data);
    }

    /**
     * 字段自增
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function increase_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return Shop::where('id', $n_id)->increment($s_field, $n_step);
    }

    /**
     * 字段自减
     *
     * @param int $n_id
     * @param string $s_field
     * @param int $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function decrease_num($n_id, $s_field = 'commend_num', $n_step = 1)
    {
        return Shop::where('id', $n_id)->decrement($s_field, $n_step);
    }


    /**
     * 获取一条记录
     * @param $where
     * @return mixed
     *
     */
    public function get_shop(int $nId)
    {
        return Shop::select('id', 'name', 'logo', 'address')->find($nId);
    }

    /**
     * 获取已经开通都的省份列表
     */
    public function get_open_province()
    {
        return Shop::select('province')
            ->with(['province_name'])
            ->where('province', '>', 0)->groupBy('province')->get()->toarray();
    }


    /**
     * 获取已经开通都的城市列表
     */
    public function get_open_city()
    {
        return Shop::select('city')
            ->with(['city_name'])->where('status', 1)
            ->where('city', '>', 0)->groupBy('city')->get()->toarray();
    }
}